<script setup lang="ts">
import OrderRequest from '@/request/orderRequest';
import { useAppStore, useControllerStore } from '@/store';
import eventBus from '@/utils/eventBus';
import { navigate } from '@/utils/navigate';
import Tools from '@/utils/tools';

const store = useAppStore();
const { btnInformation, beeperId, beeperParams } = store.$state;
const show = ref<boolean>(false);
const voicePath = ref<string>('');
const voiceKey = ref<string>('');
const progress = ref<number>(1);
const play = ref<boolean>(false);
const voiceDuration = ref<number>(1000 * 30);
const recorderManager = uni.getRecorderManager();
const recordingModalText = ref<string>('');
const innerAudioContext = uni.createInnerAudioContext();
let interval: ReturnType<typeof setInterval> | null = null;

onLoad(() => {
  let loadInterval: ReturnType<typeof setInterval> | null = null;
  recorderManager.onStart(() => {
    loadInterval = setInterval(() => {
      progress.value += 1;
    }, 1000);
  });
  recorderManager.onError((err) => {
    voiceDuration.value = 1000 * 30;
    voicePath.value = '';
  });
  recorderManager.onStop((res) => {
    voiceDuration.value = res.duration;
    voicePath.value = res.tempFilePath;
    progress.value = 0;
    clearInterval(loadInterval!);
  });
  innerAudioContext.onEnded(() => {
    progress.value = 0;
    play.value = false;
    clearInterval(interval!);
  });
});

onMounted(() => {
  eventBus.on('callRecordingModal', handleWatchRecordingEvent);
});

onUnmounted(() => {
  eventBus.off('callRecordingModal');
});

// 观察记录事件总线
const handleWatchRecordingEvent = (params: { text?: string; visible: boolean; key: string }) => {
  const { text, visible, key } = params;
  voiceKey.value = key;
  recordingModalText.value = text || '发送订单';
  show.value = !!visible;
  if (visible) {
    voiceDuration.value = 1000 * 30;
    voicePath.value = '';
    recorderManager.start({ duration: 1000 * 30 });
  } else {
    voiceDuration.value = 1000 * 30;
    voicePath.value = '';
    recorderManager.stop();
    if (interval) clearInterval(interval);
  }
};

// 播放录音
const handlePlayVoice = () => {
  play.value = !play.value;
  if (play.value) {
    innerAudioContext.obeyMuteSwitch = false;
    innerAudioContext.src = voicePath.value;
    innerAudioContext.play();
    interval = setInterval(() => {
      progress.value += 1;
    }, 1000);
  } else {
    innerAudioContext.pause();
    clearInterval(interval!);
  }
};

// 计算进度
const calculatePercentage = (progress: number, total: number): number => {
  if (progress === 1000) return 5;
  const percentage = (progress / total) * 100;
  return Number(percentage.toFixed(2));
};

// 提交录音数据
const handleSubmit = async () => {
  show.value = false;
  // 发送语音订单
  if (voiceKey.value === 'voiceOrdering') {
    const params = {
      audio: (await Tools.uniBase64FromFile(voicePath.value)).toString(),
      beeperId,
      btnId: btnInformation!.id,
      queryType: beeperParams!.queryType,
      btnServerClassifyIds: btnInformation!.classifyIds,
      btnType: btnInformation!.btnType,
    };
    OrderRequest.SendVoiceOrder({ ...params, hasLoading: true }).then(() => {
      navigate({ url: '/pages/order/index', type: 'switchTab' });
    });
  } else {
    const recordingTempFilePath = useControllerStore().$state.recordingTempFilePath;
    recordingTempFilePath.push({ key: voiceKey.value, value: voicePath.value });
    useControllerStore().$patch({ recordingTempFilePath });
  }
};
</script>

<template>
  <van-popup :show="show" @close="show = false">
    <view class="c-br c-pd w-screen flex justify-center">
      <view class="c-br bg-white c-pd w-full flex flex-col items-center overflow-hidden">
        <i v-if="!voicePath" class="i-fa-solid:microphone c-color-sec text-[50px]" />
        <i v-else :class="play ? 'i-icon-park-solid:pause-one' : 'i-icon-park-solid:play'" class="c-color-sec text-[80px] mb-[12px]" @click="handlePlayVoice" />
        <text class="c-color-sec mt-[8px]" v-show="!voicePath">录音中，请说出你的需求...</text>
        <view class="w-full my-[22px]" v-show="progress">
          <van-progress :percentage="calculatePercentage(progress * 1000, voiceDuration)" :pivot-text="progress ? progress + '秒' : ''" color="#ea622c" />
        </view>
        <van-button v-if="voicePath" type="primary" :color="'#ea622c'" block class="w-full" @click="handleSubmit">
          {{ recordingModalText }}
        </van-button>
        <van-button v-else type="primary" :color="'#ea622c'" block class="w-full" @click="recorderManager.stop()"> 停止录音 </van-button>
      </view>
    </view>
  </van-popup>
</template>
